package org.glut.backend.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: gluglu2
 * @date: 2025/8/4 10:42
 */
@RestController
public class SlideCaptchaController {

    @Value("${aliyun.captcha.app-id}")
    private String captchaAppId;

    @Value("${aliyun.captcha.app-secret}")
    private String appSecretKey;

    @Value("${aliyun.captcha.app-code}")
    private String appCode;

    /**
     * @description: 滑动验证码后端调用api验证
     * @param request
     * @param httpRequest
     * @return org.springframework.http.ResponseEntity<java.util.Map<java.lang.String,java.lang.Object>>
     * @author: gluglu2
     * @date: 2025/8/4 10:42
     */
    @PostMapping("/SlideCaptchaVerify")
    public ResponseEntity<Map<String, Object>> verifyCaptcha(
            @RequestBody CaptchaVerifyRequest request,
            HttpServletRequest httpRequest) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 构造请求URL
            String url = "https://fscaptcha.market.alicloudapi.com/";

            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "APPCODE " + appCode);
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 构造请求体
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("CaptchaAppId", captchaAppId);
            body.add("AppSecretKey", appSecretKey);
            body.add("RandStr", request.getRandStr());
            body.add("Ticket", request.getTicket());
            body.add("UserIp", getClientIp(httpRequest));

            // 发送验证请求
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            // 解析响应
            JSONObject responseBody = JSONObject.parseObject(response.getBody());
            if (responseBody != null && "200".equals(responseBody.getString("code"))) {
                JSONObject data = responseBody.getJSONObject("data");
                if ("1".equals(data.getString("CaptchaCode"))) {
                    result.put("success", true);
                    result.put("message", "验证通过");
                    return ResponseEntity.ok(result);
                } else {
                    result.put("success", false);
                    result.put("message", "验证失败: " + data.getString("CaptchaMsg"));
                    return ResponseEntity.badRequest().body(result);
                }
            } else {
                result.put("success", false);
                result.put("message", "验证服务返回错误: " + (responseBody != null ? responseBody.getString("msg") : "未知错误"));
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "验证服务异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    // 获取客户端真实IP
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 前端传来的数据格式，封装为静态内部类
     */
    @Data
    public static class CaptchaVerifyRequest {
        private String ticket;
        private String randStr;
    }

}
